package com.citycloud.ccuap.tc.admin.filter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class HeaderRequestWrapper extends HttpServletRequestWrapper {
	private Map<String, String> headerMap = new HashMap<>();

	private Map<String, String[]> params = new HashMap<>();

	/**
	 * construct a wrapper for this request
	 *
	 * @param request
	 */
	public HeaderRequestWrapper(HttpServletRequest request) {
		super(request);
		//将参数表，赋予给当前的Map以便于持有request中的参数
		this.params.putAll(request.getParameterMap());
	}

	/**
	 * add a header with given name and value
	 * 
	 * @param name
	 * @param value
	 */
	public void addHeader(String name, String value) {
		headerMap.put(name, value);
	}

	@Override
	public String getHeader(String name) {
		String headerValue = super.getHeader(name);
		if (headerMap.containsKey(name)) {
			headerValue = headerMap.get(name);
		}
		return headerValue;
	}

	/**
	 * get the Header names
	 */
	@Override
	public Enumeration<String> getHeaderNames() {
		List<String> names = Collections.list(super.getHeaderNames());
		for (String name : headerMap.keySet()) {
			names.add(name);
		}
		return Collections.enumeration(names);
	}

	@Override
	public Enumeration<String> getHeaders(String name) {
		List<String> values = Collections.list(super.getHeaders(name));
		if (headerMap.containsKey(name)) {
			values.add(headerMap.get(name));
		}
		return Collections.enumeration(values);
	}


	@Override
	public Enumeration<String> getParameterNames() {
		return Collections.enumeration(new ArrayList<>(params.keySet()));
	}

	/**
	 * 重写getParameter方法
	 *
	 * @param name 参数名
	 * @return 返回参数值
	 */
	@Override
	public String getParameter(String name) {
		String[] values = params.get(name);
		if (values == null || values.length == 0) {
			return null;
		}
		return values[0];
	}

	@Override
	public String[] getParameterValues(String name) {
		String[] values = params.get(name);
		if (values == null || values.length == 0) {
			return null;
		}
		return values;
	}

	/**
	 * 增加多个参数
	 *
	 * @param otherParams 增加的多个参数
	 */
	public void addAllParameters(Map<String, Object> otherParams) {
		for (Map.Entry<String, Object> entry : otherParams.entrySet()) {
			addParameter(entry.getKey(), entry.getValue());
		}
	}

	/**
	 * 增加参数
	 *
	 * @param name  参数名
	 * @param value 参数值
	 */
	public void addParameter(String name, Object value) {
		if (value != null) {
			if (value instanceof String[]) {
				params.put(name, (String[]) value);
			} else if (value instanceof String) {
				params.put(name, new String[]{(String) value});
			} else {
				params.put(name, new String[]{String.valueOf(value)});
			}
		}
	}
}
